package com.yzh.openai.domain.openai.service.rule.impl;

import com.alibaba.fastjson.JSON;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import com.yzh.openai.domain.openai.annotation.LogicStrategy;
import com.yzh.openai.domain.openai.model.aggregates.ChatProcessAggregate;
import com.yzh.openai.domain.openai.model.entity.MessageEntity;
import com.yzh.openai.domain.openai.model.entity.RuleLogicEntity;
import com.yzh.openai.domain.openai.model.entity.UserAccountEntity;
import com.yzh.openai.domain.openai.model.valobj.LogicCheckTypeVO;
import com.yzh.openai.domain.openai.service.rule.ILogicFilter;
import com.yzh.openai.domain.openai.service.rule.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 敏感词过滤
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.SENSITIVE_WORD)
public class SensitiveWordFilter implements ILogicFilter<UserAccountEntity> {
    @Resource
    private SensitiveWordBs words;

    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcess, UserAccountEntity data) throws ExecutionException {
        //若检测出敏感词则响应用户【检测到您的语言有违规用词，请重新提问！】
        List<MessageEntity> messages = chatProcess.getMessages();
        String content = messages.get(messages.size() - 1).getContent();    //获取最后一条提问信息
        if (words.contains(content)) {
            List<String> all = words.findAll(content);
            log.info("检测到违规词：{}", JSON.toJSONString(all));
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.REFUSE)
                    .info("❌检测到您的语言有违规用词，请重新提问❌")
                    .build();
        }

        //正常放行
        return RuleLogicEntity.<ChatProcessAggregate>builder()
                .type(LogicCheckTypeVO.SUCCESS)
                .data(chatProcess)
                .build();
    }
}
